package org.socialtourist.web.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.socialtourist.web.shared.data.Image;

/*
 * The contents of this file is based in part on the stacktrace thread
 * http://stackoverflow.com/questions/1111130/basic-file-upload-in-gwt
 * 
 * Question/Answer was provided by stacktrace users Maksim/KevMo.
 * 
 */
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator iter = upload.getItemIterator(request);

			while (iter.hasNext()) {
				FileItemStream item = iter.next();

				String name = item.getFieldName();
				InputStream stream = item.openStream();

				// Process the input stream
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				int len;
				byte[] buffer = new byte[8192];
				while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
					out.write(buffer, 0, len);
				}

				int maxFileSize = (1024 * 1024); // 10 megs max
				if (out.size() > maxFileSize) {
					throw new RuntimeException("File is > than " + maxFileSize);
				}
				
				Image image = makeImage(out.toByteArray(), item.getContentType());
				Long id = persistImage(image);
				
				//response.setContentType("text/html");
				Writer writer = new OutputStreamWriter(response.getOutputStream());
				writer.write("<p>"+id.toString()+"</p>");
				writer.close();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	private Long persistImage(Image image) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			pm.makePersistent(image);
			
		} finally {
			pm.close();
		}
		
		return image.getId();
	}

	private Image makeImage(byte[] data, String contentType) {
		Image image = new Image();

		checkContentType(contentType);
		image.setImageType(contentType);

		image.setImage(data);
		return image;
	}

	private void checkContentType(String contentType) {
		if(contentType.equals("image/png") ||
				contentType.equals("image/jpg"))
			return;
		throw new RuntimeException("Unsupported content type " + contentType);
		
	}
}